package com.freedom.org.service.impl;

import com.freedom.base.service.impl.BaseServiceImpl;
import com.freedom.org.domain.Department;
import com.freedom.org.mapper.DepartmentMapper;
import com.freedom.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 开启事务
 *
 * @author freedom
 */
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void insert ( Department department ) {
        departmentMapper.insert(department);
        this.insertOrUpdateHandler(department);
        departmentMapper.update(department);
    }

    @Override
    public void update ( Department department ) {
        departmentMapper.update(department);
    }

    /**
     * 新增 修改 处理返回数据
     */
    public void insertOrUpdateHandler ( Department department ) {
        if (Objects.isNull(department.getParent().getId())) {
            // id为空 没有上级
            department.setPath("/" + department.getId());
        } else {
            // 有id，有上级
            Department parent = departmentMapper.getById(department.getParent().getId());
            department.setPath(parent.getPath() + "/" + department.getId());
        }
    }
}
